//148.排序链表
//给你链表的头结点 head ，请将其按 升序 排列并返回 排序后的链表 。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        // 归并排序
        // 先分后治
        return MergeSort(head, nullptr);
    }

    ListNode* MergeSort(ListNode* head, ListNode* tail) {
        // 如果没有节点了或者只有一个节点就返回
        if (head == nullptr) {
            return head;
        }
        if (head->next == tail) {
            head->next = nullptr;
            return head;
        }

        // 分即寻找中间节点
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast != tail && fast->next != tail) {
            fast = fast->next->next;
            slow = slow->next;
        }
        ListNode* mid = slow;
        return merge(MergeSort(head, mid), MergeSort(mid, tail));
    }

    ListNode* merge(ListNode* list1, ListNode* list2) {
        // 治即将两个有序链表连接起来
        ListNode* newnode = new ListNode(0, nullptr);
        ListNode* node = newnode;
        ListNode* tmp1 = list1;
        ListNode* tmp2 = list2;
        while (tmp1 != nullptr && tmp2 != nullptr) {
            if (tmp1->val < tmp2->val) {
                node->next = tmp1;
                tmp1 = tmp1->next;
            } else {
                node->next = tmp2;
                tmp2 = tmp2->next;
            }
            node = node->next;
        }
        if (tmp1 != nullptr) {
            node->next = tmp1;
        } else if (tmp2 != nullptr) {
            node->next = tmp2;
        }
        return newnode->next;
    }
};